(function() {


    var global = {
        validation : {
                         isNum : function(val){
                                     var re = /^[0-9]\d*$/;
                                     if (!re.test(val)) {
                                         return false;
                                     }else{
                                         return true;
                                     }
                         }
                     },
       iptSel : function(o,fn){
                   o.each(function(i){
                      var t = $(this), b = t.find('sub'), p = t.find('sup'), v = t.find('input');
                      b.click(function(){
                          val = parseInt(v.val());
                          if(!global.validation.isNum(val)){
                              Tgm.callback(fn,[false]);
                          }else{
                              v.val(val+1);
                              Tgm.callback(fn,[true]);
                          }
                      });
                      p.click(function(){
                          val = parseInt(v.val());
                          if(!global.validation.isNum(val)){
                              Tgm.callback(fn,[false]);
                          }else{
                            if(val == 0){
                              Tgm.callback(fn,[false]);
                              return;
                            }
                            v.val(val-1);
                              Tgm.callback(fn,[true]);
                          }
                      });
                   })
                },
       iptText:function(o,fn){
           
           },
       iptDate:function(o,fn){
                  o.each(function(i){
                    $(this).eq(i).datepicker(); 
                  })
               },
       iptValidation:function(t){//表单统一校验
                   var flag = true, v = t.val(); c = t.data('validation') , l = t.data('limit') , tip = t.data('tip') , e = t.data('empty');
                   //alert(tip);
                   v = $.trim(v);
                   if(!e){
                       if( v == ''){
                         $('#tgm_tip_0').html(tip).show();
                         flag = false;
                       }
                   }
                   if(c == 'isnum'){
                       if( !global.validation.isNum(v)){
                           flag = false;
                       }else{
                           if(l.length > 0){
                               ls = l.split(',');
                               //alert(ls[0] + '====' + v + '====' + ls[1]);
                               if(((ls[0] - v) >0) || ((v - ls[1])>0)){
                                   flag = false;
                               }
                           }
                       }
                   }
                    if(!flag){ 
                       $('#tgm_tip_0').html(tip).show();
                       if(t.parent().hasClass('tgm-ipt-0')){
                          t.parent().addClass('ipt-e');
                       }else{
                          t.addClass('ipt-e');
                       }
                    }
                  return flag;
               }
    };
    Tgm.reg('Global',global);
    var tgmCond = {
        mainTabsChg : function(){
                          var tgmCondTab = $('#tgm_cond_tab');
                          tgmCondTab.find('ul li a').click(function(){
                              tgmCondTab.find('ul li a').removeClass('active');
                              $(this).addClass('active');
                              Tgm.set('tabid',$(this).data('tab_id'));
                              tgmCond.menuLoad();
                              return false;
                          })            
                          Tgm.set('tabid',tgmCondTab.find('ul li a').eq(0).data('tab_id'));
                          tgmCond.menuLoad();
                      },
        menuLoad : function(){
                      Tgm.ajax('submenu',{
                           url: Tgm.menuurl,
                       dataType: 'json',
                       data: {"tabid":Tgm.get('tabid')},
                       success: function(data){
                           Tgm.set('menuJson',data);
                           tgmCond.menuCreate();
                       }
                       });

                   },
        menuCreate:function(){
                       var menuJson = Tgm.get('menuJson'), html = [],len = menuJson.length, cls = '',id = Tgm.id(), firstMenuId = 0;
                       html.push('<ul id="',id,'">');
                       if(len > 0){
                           for(var i=0; i < len; i++){
                               cls = (i == 0 )? 'tgm-tabs-left-open':'';
                               html.push('<li><a class="tgm-tabs-left-item ', cls ,'" href="#" data-menu_id = "', menuJson[i].id ,'">', menuJson[i].name ,'</a>');
                               if(menuJson[i].children)
                               {
                                   var subMenuJson =  menuJson[i].children , sublen = subMenuJson.length;
                                   cls = (i == 0 )? '':' hide';
                                   html.push('<ul  class="tgm-tabs-left-sub ',cls,'">');
                                   for(var j=0; j < sublen; j++){	
                                       if( j == 0 && i == 0)
                                       {
                                           cls = 'active'; 
                                           firstMenuId = subMenuJson[j].id;
                                       }else{
                                           cls = '';
                                       }
                                       html.push('<li><a class="tgm-tabs-left-sub-item ', cls ,'" href="#" data-sub_menu_id = "', subMenuJson[j].id ,'">', subMenuJson[j].name ,'</a>');
                                   }
                                   html.push('</ul>');
                               }
                               else
                               {
                                   html.push('</li>');
                               }
                           }
                       }
                       html.push('</ul>');
                       $('#tgm_tabs_left').html(html.join(''));
                       if(firstMenuId > 0){   //第一节点载入右侧内容
                           Tgm.set('subMenuId',firstMenuId);	
                           tgmCond.condLoad();//加载右侧内容
                       }
                       var subMenu = $('#'+id);
                       subMenu.click(function(e){
                           tar = e.target;
                           currNode = $(e.target);
                           if(currNode.hasClass('tgm-tabs-left-open')){
                               currNode.removeClass('tgm-tabs-left-open');
                               currNode.parent().find('ul').hide();
                           }else if(currNode.hasClass('tgm-tabs-left-item')){
                               var o = subMenu.find('.tgm-tabs-left-open');
                               o.parent().find('ul').hide();
                               o.removeClass('tgm-tabs-left-open')
                           currNode.addClass('tgm-tabs-left-open');
                       currNode.parent().find('ul').show();
                           }else if(currNode.hasClass('tgm-tabs-left-sub-item')){
                               var subMenuId = currNode.data('sub_menu_id');
                               Tgm.set('subMenuId',subMenuId);
                               var o = subMenu.find('.tgm-tabs-left-sub-item');
                               o.removeClass('active')
                           currNode.addClass('active');
                       tgmCond.condLoad();//加载右侧内容
                           }
                           return false;
                       });
                   },
        /*加载条件选择面板*/
        condLoad:function(){
                     var subMenuId = Tgm.get('subMenuId'), ct = $('#tgm_conditions_select');//当前菜单编号
                     ct.load(Tgm.conddetailurl, {submenuid: subMenuId}, function() {
                         //初始化输入内容
                         tgmCond.condFormInit();
                     });
                 },
        condFormInit:function(){
                         var form = $('#tgm_cond_form'),iptSel = form.find('.tgm-ipt-0'),flag = true;
                         Tgm.Global.iptSel(iptSel,function(data){
                             var v = iptSel.find('input'),tip = v.data('tip');
                               if(!data){
                                   $('#tgm_tip_0').html(tip).show();
                                   iptSel.addClass('ipt-e');
                               }else{
                                   $('#tgm_tip_0').html(tip).hide();
                                   iptSel.removeClass('ipt-e');
                               }
                         });
                          form.find('input').each(function(i){
                                   var t = $(this);
                                   if(t.hasClass('datepicker')){
                                       t.datepicker();
                                       t.datepicker('option','dateFormat','yy-mm-dd');
                                   }
                                   $(this).focus(function(){
                                     $('#tgm_tip_0').hide();
                                     iptSel.removeClass('ipt-e');
                                     $(this).removeClass('ipt-e');
                                     flag = true;
                                   }).blur(function(){
                                       //Tgm.Global.iptValidation($(this));
                                   });
                          })
                         form.find('.submit').click(function(){
                                    form.submit();
                         })
                         form.submit(function(){
                             flag = true;
                             var tVal = '';
                             form.find('input').each(function(i){
                                 //判断范围
                                 flag = Tgm.Global.iptValidation($(this));
                                 tVal = $(this).val();
                                 return flag;
                             });
                             if(flag){
                                 if(Tgm.get('win_select_cond')){
                                     Tgm.ajax('resultModifyCond',{
                                         url: Tgm.savecondurl,
                                         dataType: 'json',
                                         data: form.serialize(),
                                         success: function(data){
                                             var v = self.parent.document.getElementById('frequency');
                                             self.parent.document.getElementById('frequency').innerHTML = (v.innerHTML -1);
                                             self.parent.Tgm.CurrCond = tVal;
                                             self.parent.Tgm.TgmResult.init();                                    
                                             self.parent.Tgm.sWin.unrender();
                                         }
                                     });
                                     return false;
                                 }
                             } 
                             return flag;
                         })
                     },
        init:function(){
                 tgmCond.mainTabsChg();
             }
    };
    Tgm.reg('TgmCond', tgmCond);

    var tgmResult= {
        listScroll:function(){
                    $('#tgm_table_scroll_body').scroll(function(){
                           var l = $(this).scrollLeft();                    
                           $('#tgm_table_scroll_head').scrollLeft(l);//
                           //setTimeout(function(){
                               //$('#tgm_table_scroll_head').scrollLeft(l);
                           //},0)
                    }) 
        },
        dataLoad:function(){
                     Tgm.ajax('resultlist',{
                         url: Tgm.resultlisturl,
                         dataType: 'json',
                         data: Tgm.CurrCond,
                         success: function(data){
                            Tgm.set('resultJson',data);
                            tgmResult.render();
                         }
                     });
                 
        },
        html :{
                thead:function(){
                   var thead = Tgm.get('resultJson').thead,len = thead.length,html = [],cls = '';
                    html.push('<table class="tgm-table-1"><thead><tr>');
                    for(var i = 0; i<len ; i++){
                        cls = ( thead[i].sort == 'none') ? '' : 'sort-'+ thead[i].sort;
                        html.push('<th><span class="item"><span class="',cls,'">',thead[i].text,'</span></span></th>');
                    }
                    html.push('</tr></thead></table>');
                    return html.join('');
                 },
                tbody:function(){
                    var tbody = Tgm.get('resultJson').tbody,len = tbody.length,html = [],cls = '',ccls = '';
                    html.push('<table class="tgm-table-1"><tbody>');
                    for(var i = 0; i<len ; i++){
                        //console.log(tbody[i].color);
                        cls = ( tbody[i].color == '') ? '' : tbody[i].color;
                        slen = tbody[i].data.length;
                        d = tbody[i].data;
                         if(i == 0){
                                 Tgm.set('selectedRorderID',tbody[i].id);
                                 ccls = ' active';
                         }else{
                                 ccls = ' ';
                         }
                        html.push('<tr data-id="',tbody[i].id,'" class="',ccls,'">');
                        for(var j = 0; j < slen; j++){
                            ccls = (j > 0) ? cls:'';
                            html.push('<td><span class="',ccls,'">',d[j],'</span></td>');
                        }
                        html.push('</tr>');
                    }
                    html.push('</tbody></table">');
                    return html.join('');     
                },
                tfoot:function(){
                       var total = Tgm.get('resultJson').total,html = '',end;
                       if( total > Tgm.ResultOnceNum){
                           if( (total - Tgm.ResultOnceNum) > Tgm.ResultOnceNum){
                              moreRecord = (Tgm.ResultOnceNum+1) + ' - ' + (Tgm.ResultOnceNum * 2);
                           }else{
                              moreRecord = (Tgm.ResultOnceNum+1) + ' - ' + total;
                           }
                           Tgm.set('start',Tgm.ResultOnceNum);
                           return '<span class="leave">共'+total+'笔</span><span id="get_more_record"><a href="#">点击获取更多（'+moreRecord+'）</a></span>';
                       }else{
                          return '<span class="leave">共'+total+'笔</span>';
                       }
                 },
                 condDesc:function(){
                           var condList = Tgm.get('resultJson').conddesc,len = condList.length;html = '' ,i = 0;
                           if(len > 2){
                             html += '<span class="tgm-cond-item tgm-cond-more">...</span>';
                             i = len - 2;
                           }
                           for(i; i < len; i++){
                             html += '<span class="tgm-cond-item">' + condList[i] + '</span>';
                           }
                           return html;
                    }
              },
        getMoreRcordNum:function(){
                            var total = Tgm.get('resultJson').total,str = '', end = 0;
                             if(!Tgm.get('start')){
                                    Tgm.set('start',Tgm.ResultOnceNum);  //第几条开始 
                              }
                             if(total >= Tgm.get('start')){
                                 if(total - Tgm.get('start') > Tgm.ResultOnceNum){
                                    Tgm.set('start', Tgm.get('start') + Tgm.ResultOnceNum)
                                     end = (Tgm.get('start') + Tgm.ResultOnceNum) > total ? total : Tgm.get('start') + Tgm.ResultOnceNum;
                                 }else{
                                    Tgm.set('start', total);
                                    end = total;
                                 }
                             }
                             if(Tgm.get('start')+1 > total){
                                 str = '已全部显示';
                             }else{
                                 str = '<a href="#">点击获取更多（'+(Tgm.get('start')+1) + ' - ' + end+'）</a>';
                             }
                             return str; 
                        },
        render:function(){
                   $('#tgm_cond_list').html(tgmResult.html.condDesc);
                   $('#tgm_table_scroll_head').html(tgmResult.html.thead());
                   $('#tgm_table_scroll_body').html(tgmResult.html.tbody());
                   $('#tgm_table_foot').html(tgmResult.html.tfoot());
                   /*点击列表数据*/
                   var tbody = $('#tgm_table_scroll_body table').eq(0),t;
                   tbody.click(function(e){
                       var tar = e.target,id = 0;
                       while(true){
                           currNode=$(tar);
                           if(currNode.get(0).tagName.toLowerCase() == 'tr'){
                               id = currNode.data('id');
                               Tgm.set('selectedRorderID',id);
                               tbody.find('tr').removeClass('active');
                               currNode.addClass('active');
                               tgmResult.chartsLoad();
                               break;
                           }
                           tar = currNode.parent()[0];
                       }
                   });
                 tgmResult.tabsInit();

                 /*点击更多*/
                 $('#get_more_record').click(function(){
                     if(Tgm.get('start') == Tgm.get('resultJson').total){
                         return false;
                     }
                      Tgm.ajax('resultMoreRecord',{
                           url: Tgm.resultlistmoreurl,
                       dataType: 'json',
                       data: {"start":Tgm.get('start'),"limit":Tgm.ResultOnceNum},
                       success: function(data){
                           Tgm.set('moreRecordJson',data);
                           tgmResult.moreAppend();
                          document.getElementById('tgm_table_scroll_body').scrollTop = 10000;
                           var s = tgmResult.getMoreRcordNum();
                           $('#get_more_record').html(s);
                       }
                       });
                     
                     return false;
                 })
                 /*保存选股条件*/
                 $('#tgm_cond_save').click(function(){
                   if(!Tgm.get('isWinCond')){
                     Tgm.win = new Tgm.Window({width:350,height:250});
                     var html = [];
                     html.push('<div  class="tgm-cond-save-content"><p>请选择分组：</p><p><select id="select_group" name="select_group"><option value="1" selected="true">选股组合一</option><option value="2">选股组合二</option><option value="3">选股组合三</option></select></p><p class="opt"><a href="#" class="tgm-btn-0" id="tgm_cond_save_btn"><span style="color:#fff">保存</span></a><a href="#" class="tgm-btn-3" id="tgm_cond_cancel_btn"><span style="color:#222">取消</span></a></p></div>');
                     Tgm.win.hideFooter().setContent(html.join('')).render();
                     Tgm.set('isWinCond',true);
                   }else{
                       Tgm.win.render();
                   }
                     $('#tgm_cond_save_btn').click(function(){
                         var t = $('#select_group').val();
                         Tgm.ajax('saveCond',{
                             url: Tgm.savecondurl,
                             dataType: 'json',
                             data: {"id":t},
                             success: function(data){
                                 if(data.success){
                                     alert('保存成功');
                                 } 
                                 Tgm.win.unrender();
                             }

                         });
                     });
                     $('#tgm_cond_cancel_btn').click(function(){Tgm.win.unrender()});
                     return false;
                 });
                 /*添加选股条件*/ 
                  $('#tgm_cond_add').click(function(){
                    if(!Tgm.get('isWinAddCond')){
                     Tgm.sWin = new Tgm.Window({title:'添加选股条件',width:780,height:550});
                     Tgm.sWin.hideFooter().setContent('<iframe src="selectcond.html" id="tgm_cond_frame" width="100%" height="100%" scroll="0"></iframe>').render();
                     Tgm.set('isWinAddCond',true);
                   }else{
                       Tgm.sWin.render();
                       //if(Tgm.ie){
                       var thisIframe = document.getElementById('tgm_cond_frame');
                       thisIframe.src = thisIframe.src;
                       //}
                   }
                     return false;
                 });

                   
               },
        moreAppend:function(){
             var tbody = Tgm.get('moreRecordJson'),len = tbody.length,slen = 0,html = [],cls,ccls;           
             for(var i = 0; i<len ; i++){
                        cls = ( tbody[i].color == '') ? '' : tbody[i].color;
                        slen = tbody[i].data.length;
                        d = tbody[i].data;
                        html.push('<tr data-id="',tbody[i].id,'">');
                        for(var j = 0; j < slen; j++){
                            ccls = (j > 0) ? cls:'';
                            html.push('<td><span class="',ccls,'">',d[j],'</span></td>');
                        }
                        html.push('</tr>');
                }
                $('#tgm_table_scroll_body table tbody').append(html.join(''));
        },
        tabsInit :function(){
                          var tgmResultTab = $('#tgm_results_charts_tab');
                          tgmResultTab.find('ul li a').click(function(){
                              tgmResultTab.find('ul li a').removeClass('active');
                              $(this).addClass('active');
                              Tgm.set('resultType',$(this).data('type'));
                              tgmResult.chartsLoad();
                              return false;
                          })            
                          Tgm.set('resultType',tgmResultTab.find('ul li a').eq(0).data('type'));
                          tgmResult.chartsLoad();
                 
                 },
        chartsLoad:function(){
                       /**
                        *resultType: 当前tab类型根据
                        */
                      var t = Tgm.get('selectedRorderID'),type = Tgm.get('resultType');
                      if(!t){
                          alert('请先选择股票!');
                          return;
                      }
                      Tgm.ajax('resultDetail',{
                           url: Tgm.resultdetailurl,
                           dataType: 'json',
                           data: {"id":t},
                           success: function(data){
                              Tgm.set('resultDetailInfo',data);
                               tgmResult.detailInfoShow();
                           }

                       });
                   
                   },
        detailInfoShow:function(){
                         var json = Tgm.get('resultDetailInfo'),html = '',len = json.info.length;
                         if(json){
                            html =  '<span class="id">'+json.id+'</span><span class="name">'+json.name+'</span>';
                            $('#tgm_current_title').html(html);
                            html = ' <img src="'+json.chart+'" width="487" alt="" />';
                            $('#tgm_charts_detail').html(html);
                            html = '<ul>';
                            for(var i = 0; i < len; i++){
                                html += '<li>' + json.info[i].name + '：' + json.info[i].value + '</li>';
                            }
                            html += "</ul>";
                           $('#tgm_charts_intro').html(html); 
                         }
                       },
        saveCond:function(){

                 },
        init:function(){
               tgmResult.listScroll();
               tgmResult.dataLoad();
               $('#tgm_cond_save').click(function(){
                 tgmResult.saveCond();
               });
             }
    }
    Tgm.reg('TgmResult', tgmResult);

    var tgmManager= {
        tabsChg:function(){
                 var t = $('#tgm_group_tabs'); 
                 t.find('ul li a').click(function(){
                     t.find('ul li a').attr('class','tgm-tabs-left-item');
                     $(this).attr('class','tgm-tabs-left-sub-item active');
                     $('#tgm_breacrumbs').find('span').eq(1).text($(this).text());
                     Tgm.set('groupId',$(this).data('group_id'));
                     
                      $('#tgm_cond_exec').attr('href',Tgm.resulturl + '?id =' + Tgm.get('groupId'));
                     //alert(Tgm.get('groupId'));
                 })
                 var cgroupId = t.find('ul li a:first').data('group_id');
                 Tgm.set('groupId',cgroupId);
                 $('#tgm_cond_exec').attr('href',Tgm.resulturl + '?id =' + cgroupId);

                },
        condListLoad:function(){
                         Tgm.ajax('groupCond',{
                             url: Tgm.managercondlisturl,
                             dataType: 'json',
                             data: {"id":Tgm.get('groupId')},
                             success: function(data){
                                Tgm.set('groupCond',data);
                                tgmManager.listInit();
                             }
                         });
                     },
        listInit:function(){
                    var t = Tgm.get('groupCond'),len = t.length,html = [];
                    html.push('<table class="tgm-table-2">')
                    for(var i = 0; i < len ; i++){
                         html.push('<tr ><td><span class="desc">', i + 1 ,'、', t[i].desc ,'<span class="sy">></span>5元</span></td><td class="opt"><a href="#" class="modify" data-cond-id="',t[i].id,'">修改</a><span class="sp">|</span><a href="#" class="delete" data-cond-id="',t[i].id,'">删除</a></td></tr>');
                    }
                    html.push('</table>');
                    $('#tgm_group_cond_list').html(html.join(''));
                    $('#tgm_group_cond_list tr').click(function(){
                         $('#tgm_group_cond_list tr').removeClass('active');
                         $(this).addClass('active');
                    });

                    $('#tgm_group_cond_list').click(function(e){
                           tar = e.target;
                          currNode = $(e.target);
			  if(currNode.get(0).tagName.toLowerCase() == 'a'){
				  var cId = currNode.data('cond-id'),html = '';

				  if(currNode.attr('class') == 'delete'){
					  if(confirm('您确认删除该条件吗？')){
						  Tgm.ajax('delcond',{
							  url: Tgm.delcondurl,
							  dataType: 'json',
							  data: {id:cId},
							  success: function(data){
								  alert('删除成功');
								  tgmManager.listInit();
							  }
						  });
					  }
				  }else{
					  if(!Tgm.get('isWinAddCond')){
						  Tgm.sWin = new Tgm.Window({title:'修改选股条件',width:400,height:350});
						  Tgm.set('isWinAddCond',true);
					  }
					  Tgm.ajax('resultlist',{
						  url: Tgm.modifycondurl,
						  dataType: 'html',
						  data: {id:cId},
						  success: function(data){
							  Tgm.sWin.setContent('<div class="modifyCond">'+ data +'</div>').render();
							  tgmCond.condFormInit();
							  //保存修改
							  $('#btn-save').click(function(){
								  var flag = true;
								  var tVal = '';
								  var form = $('#tgm_cond_form');
								  form.find('input').each(function(i){
									  if($(this).data('validation') == 'isnum'){
										  if(!Tgm.Global.validation.isNum($(this).val()) || ($(this).val() < 0)){
											  $('#tgm_tip_0').show();
											  flag = false;
										  }
										  tVal = $(this).val();
									  }
								  });
								  if(flag){
									  Tgm.ajax('savecond',{
										  url: Tgm.savecondurl,
										  dataType: 'json',
										  data: {id:cId,val:tVal},
										  success: function(data){
											  alert('保存成功');
											  Tgm.sWin.unrender();
											  tgmManager.listInit();
										  }
									  });
								  }

							  })
						  }
					  });
				  }
				  /////////////////////////
			  }
                    });

                 },
        init:function(){
                 tgmManager.tabsChg();
                 tgmManager.condListLoad();
                 //执行选股
             }

    }
    Tgm.reg('TgmManager', tgmManager);
    var tgmHome = {
        init:function(){
                 Tgm.TgmCond.init();
             }
    }
    Tgm.reg('TgmHome', tgmHome);
    var tgmSelectCond = {
        init:function(){
                 Tgm.set('win_select_cond',true);
                 Tgm.TgmCond.init();
             }
    }
    Tgm.reg('TgmSelectCond', tgmSelectCond);
})()
